import 'package:basic_common/app_theme.dart';
import 'package:basic_common/common_exports.dart';
import 'package:basic_common/common_utils.dart';
import 'package:basic_patient/model/patient_family_list.dart';
import 'package:basic_widgets/app_bar_widget.dart';
import 'package:basic_widgets/bg_widget.dart';
import 'package:basic_widgets/button_widget.dart';
import 'package:basic_widgets/image_widget.dart';
import 'package:basic_widgets/text_widget.dart';
import 'patient_detail_controller.dart';

class PatientDetailPage extends GetView<PatientDetailController> {
  const PatientDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: backAppbar(title: '患者详情'),
        body: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: ScreenHelper.width(15)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildHead(),
                SizedBox(
                  height: ScreenHelper.height(20),
                ),
                menuWidget(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.only(top: ScreenHelper.height(10)),
                        child: Text(
                          "家庭成员",
                          style: TextStyle(
                              color: AppTheme.dartWeakTextColor,
                              fontSize: ScreenHelper.sp(16)),
                          textAlign: TextAlign.left,
                        ),
                      ),
                    ),
                  ],
                ),
                familyList()
              ],
            ),
          ),
        ));
  }

  /// 家庭成员
  Widget familyList() {
    return GetBuilder<PatientDetailController>(
      id: 'familyList',
      builder: (controller) => Container(
        padding: EdgeInsets.symmetric(vertical: ScreenHelper.height(10)),
        decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: controller.familydataList.isEmpty
            ? Center(child: EmptyBox(title: "暂无数据"))
            : GridView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  childAspectRatio: 2,
                  crossAxisCount: 2,
                  crossAxisSpacing: 4,
                ),
                itemBuilder: (context, index) {
                  PatientFamilyData familyData =
                      controller.familydataList.value[index];
                  return buildFamilyItem(familyData);
                },
                itemCount: controller.familydataList.length,
              ),
      ),
    );
  }

  Widget buildFamilyItem(PatientFamilyData familyData) {
    String agevalue = '0';
    String birthday = familyData.birthday ?? '';
    if (birthday.isNotEmpty && birthday.contains('-')) {
      List<String> list = birthday.split('-');
      agevalue =
          CommonUtils.getAge(DateTime(int.parse(list[0] ?? '0'))).toString();
    }
    return solidConnerContainer(
        margin: EdgeInsets.all(2),
        padding: EdgeInsets.symmetric(horizontal: 4),
        child: ListTile(
          contentPadding: EdgeInsets.zero,
          minLeadingWidth: 0,
          leading: circleImg(head: familyData.avatarUrl ?? ''),
          title: Row(
            children: [
              Text(
                familyData.patientName!,
                style: TextStyle(
                    fontSize: ScreenHelper.sp(16),
                    color: AppTheme.dartTextColor),
              ),
              SizedBox(
                width: ScreenHelper.width(4),
              ),
              Text(
                '${agevalue}岁',
                style: TextStyle(fontSize: ScreenHelper.sp(14)),
              ),
              SizedBox(
                width: ScreenHelper.width(4),
              ),
              Expanded(
                child: Image.asset(
                  familyData.gender == '1'
                      ? "assets/profile/icon_sex_male.png"
                      : 'assets/profile/icon_female.png',
                  width: ScreenHelper.width(14),
                  height: ScreenHelper.width(14),
                  package: "basic_common",
                ),
              ),
            ],
          ),
          subtitle: Text(
            "关系：${controller.getRelation(familyData.relation!)}",
            style: TextStyle(fontSize: ScreenHelper.sp(14)),
          ),
        ),
        bgColor: Colors.white);
  }

  /// 菜单项
  Widget menuWidget() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: ScreenHelper.height(10)),
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          crossAxisSpacing: 10,
        ),
        itemBuilder: (context, index) {
          Map itemData = controller.menuList[index];
          return GestureDetector(
            onTap: () {
              if (index == 0) {
                Get.toNamed(itemData['path'],
                    arguments: controller.consumeNo.value);
              } else if (index == 2) {
                Get.toNamed(itemData['path'],
                    arguments: {"signNo": "2200069", "status": "已签约"});
              } else if (index == 4) {
                Get.toNamed(itemData['path'],
                    arguments: {"patientNo": controller.pData.value.patientNo});
              } else {
                Get.toNamed(itemData['path']);
              }
            },
            child: buildTopImgItem(
              isSvg: true,
              svgBgColor: Color(int.parse(itemData['color']!)),
              icon: itemData['icon']!,
              title: itemData['title']!,
            ),
          );
        },
        itemCount: controller.menuList.length,
      ),
    );
  }

  /// 头部信息
  Widget _buildHead() {
    return GetBuilder<PatientDetailController>(
      id: 'patientDetail',
      builder: (controller) => solidConnerContainer(
        height: ScreenHelper.height(100),
        width: ScreenHelper.screenWidth,
        padding: EdgeInsets.symmetric(vertical: ScreenHelper.height(4)),
        child: ListTile(
          leading: Container(
            width: ScreenHelper.width(60),
            height: ScreenHelper.height(60),
            child: Stack(
              clipBehavior: Clip.antiAlias,
              children: [
                circleImg(
                    width: 52, head: controller.pData.value.avatarUrl ?? ''),
                Positioned(
                  bottom: 0,
                  child: Container(
                    alignment: Alignment.center,
                    width: ScreenHelper.width(52),
                    height: ScreenHelper.height(24),
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(210, 242, 235, 1),
                        borderRadius: BorderRadius.circular(50)),
                    child: Text(
                      controller.pData.value.signFlag == 0 ? "未签约" : '已签约',
                      style: TextStyle(
                          color: AppTheme.primyColor,
                          fontSize: ScreenHelper.sp(12)),
                    ),
                  ),
                )
              ],
            ),
          ),
          title: Row(
            children: [
              Text(
                controller.pData.value.patientName ?? '',
                style: TextStyle(color: AppTheme.dartTextColor),
              ),
              SizedBox(
                width: ScreenHelper.width(10),
              ),
              Image.asset(
                controller.pData.value.gender == '1'
                    ? "assets/profile/icon_sex_male.png"
                    : 'assets/profile/icon_female.png',
                width: ScreenHelper.width(14),
                height: ScreenHelper.width(14),
                package: "basic_common",
              ),
              SizedBox(
                width: ScreenHelper.width(10),
              ),
              Text('${controller.age.value}岁')
            ],
          ),
          isThreeLine: false,
          subtitle: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.only(right: ScreenHelper.width(10)),
                margin: EdgeInsets.only(top: ScreenHelper.height(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.phone,
                          color: AppTheme.primyColor,
                          size: ScreenHelper.width(14),
                        ),
                        Text(controller.pData.value.phone ?? '')
                      ],
                    ),
                    SizedBox(
                      width: ScreenHelper.width(5),
                    ),
                    Row(
                      children: [
                        Text("${controller.pData.value.height ?? 0}cm"),
                        SizedBox(
                          width: ScreenHelper.width(10),
                        ),
                        Text("${controller.pData.value.weight ?? 0}kg"),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(
                height: ScreenHelper.height(5),
              ),
              Row(
                children: [
                  Text("患者标签"),
                  Expanded(
                    child: SizedBox(
                      height: ScreenHelper.height(24),
                      width: ScreenHelper.width(200),
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        shrinkWrap: true,
                        children: buildIdenity(
                            tagStr:
                                controller.pData.value.tagsFromDoctor ?? ''),
                      ),
                    ),
                  )
                ],
              )
            ],
          ),
        ),
        bgColor: Colors.white,
      ),
    );
  }

  /// 医生身份标签项
  List<Widget> buildIdenity({required String tagStr}) {
    List<Widget> tagWidgetList = [];
    if (tagStr.contains(',')) {
      List<String> tagList = tagStr.split(',');
      tagList.forEach((element) {
        tagWidgetList.add(tagItem(element));
      });
    }
    return tagWidgetList;
  }

  Widget tagItem(String tag) {
    return Container(
      alignment: Alignment.center,
      width: ScreenHelper.width(50),
      height: ScreenHelper.height(24),
      margin: EdgeInsets.symmetric(horizontal: ScreenHelper.width(4)),
      decoration: BoxDecoration(
          border: Border.all(color: AppTheme.primyColor),
          borderRadius: BorderRadius.circular(6)),
      child: Text(
        tag,
        style: TextStyle(
            color: AppTheme.primyColor, fontSize: ScreenHelper.sp(12)),
      ),
    );
  }
}
